from django.conf import settings
from django import http
from django.contrib.auth import login
from django.shortcuts import render,redirect
from django.views import View
from  QQLoginTool.QQtool import OAuthQQ
from meiduo_mall.utils.response_code import RETCODE
from .models import OAuthQQUser
from meiduo_mall.utils import meiduo_signature
from . import constants
from users.models import User


# 生成qq的登陆地址并返回服务器进行登陆验证
class OAuthQQURLView(View):
    def get(self,request):
        # 创建授权对象
        oauthqq = OAuthQQ(
            settings.QQ_CLIENT_ID,
            settings.QQ_CLIENT_SECRET,
            settings.QQ_REDIRECT_URI,
            request.GET.get('next')
        )
        # 生成授权地址
        login_url = oauthqq.get_qq_url()
        # 响应
        return http.JsonResponse({
            'code': RETCODE.OK,
            'errmsg': 'OK',
            'login_url': login_url
        })


class OAuthQQOpenidView(View):
    def get(self, request):
        code = request.GET.get('code')
        state = request.GET.get('state', '/')

        oauthqq = OAuthQQ(
            settings.QQ_CLIENT_ID,
            settings.QQ_CLIENT_SECRET,
            settings.QQ_REDIRECT_URI,
            request.GET.get('next')
        )
        # 使用code取出token
        token = oauthqq.get_access_token(code)
        # 使用token取出openid
        openid = oauthqq.get_open_id(token)
        # 判断用户是否是初次登陆
        try:
            qquser = OAuthQQUser.objects.get(openid=openid)
        except:
            '''
         未查寻到，初次授权，显示绑定页面
         将openid加密存入JS中并不显示到页面，下次通过ajax请求返回到服务器进行验证
            '''
            json_str = meiduo_signature.dumps({'openid':openid},constants.OPENID_EXPIRES)
            context = {
                'token': json_str
            }

            return render(request, 'oauth_callback.html', context)
        else:
            # 查询到，状态继续保持，返回到相关的页面
            user = qquser.user
            login(request, user)
            response = redirect(state)
            response.set_cookie('username',user.username)
            return response

        # return http.HttpResponse(openid)

    def post(self, request):
        access_token = request.POST.get('access_token')
        mobile = request.POST.get('mobile')
        pwd = request.POST.get('pwd')
        sms_code = request.POST.get('sms_code')
        state = request.GET.get('state', '/')

        # 验证处理
        openid_dict = meiduo_signature.loads(access_token, constants.OPENID_EXPIRES)
        if openid_dict is None:
            return http.HttpResponseForbidden('授权信息无效，请重新授权')
        openid = openid_dict.get('openid')
#         初次授权，对用户进行openid和user的绑定
        # 1.判断用户的手机是否存在
        try:
            user = User.objects.get(mobile=mobile)
        except:
            user = User.objects.create_user(mobile, password=pwd, mobile=mobile)
        else:
            if not user.check_password(pwd):
                return http.HttpResponseForbidden('手机号已经使用或者密码错误')
#             新建OAuthQQUser对象
        qquser = OAuthQQUser.objects.create(
            user=user,
            openid=openid
        )
        login(request, user)
        response = redirect(state)
        response.set_cookie('username', user.username)
        return response










